<template>
  <div>
    <el-dialog v-model="dialogFormVisible" :title="title" width="500" destroy-on-close :close-on-click-modal="closeOnClickModal">
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-form-item label="角色代码" prop="roleCode" :label-width="formLabelWidth">
          <el-input v-model="form.roleCode" autocomplete="off" placeholder="请输入角色代码" clearable :disabled="updateDisabled"/>
        </el-form-item>
        <el-form-item label="角色名" prop="roleName" :label-width="formLabelWidth">
          <el-input v-model="form.roleName" autocomplete="off" placeholder="请输入角色名" clearable />
        </el-form-item>
        <el-form-item label="描述" prop="remark" :label-width="formLabelWidth">
          <el-input v-model="form.remark" autocomplete="off" placeholder="请输入描述" clearable />
        </el-form-item>
        <el-form-item label="分配菜单" prop="menuIds" :label-width="formLabelWidth">
          <el-tree
            ref="treeRef"
            :data="treeData"
            show-checkbox
            default-expand-all
            node-key="id"
            check-strictly
            :props="{ children: 'children', label: 'name', value: 'id' }"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveOrUpdate">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { reactive, ref } from 'vue'
  import { saveOrUpdate, getUserInfo, toAssign, menuAll } from '~/api/acl/role'
  import { ElMessageBox } from 'element-plus'
  import { showMessage } from '~/utils/my-notification'

  const emit = defineEmits(['refreshDataList'])

  const dialogFormVisible = ref(false)
  const formLabelWidth = '80px'
  const title = ref('新建角色')
  const closeOnClickModal = ref(false)
  const updateDisabled = ref(false)
  const treeRef = ref(null)
  const treeData = ref([])

  const form = reactive({
    id: 0,
    roleCode: '',
    roleName: '',
    remark: ''
  })
  const rules = {
    roleCode: [
      { required: true, message: '角色代码不能为空!', trigger: 'blur' }
    ],
    roleName: [
        { required: true, message: '角色名称不能为空!', trigger: 'blur' }
    ]
  }

  function init(id) {
    dialogFormVisible.value = true
    // 查询所有菜单
    getMenuAll()
    if(!id) {
      // 新建
      title.value = '新建角色'
      form.id = 0
      form.roleCode = ''
      form.roleName = ''
      form.remark = ''
      updateDisabled.value = false
    } else {
      // 修改
      title.value = '修改角色'
      updateDisabled.value = true
      // 通过id查询用户信息
      queryUserInfo(id)
      // 查询角色分配的菜单
      queryRoleMenu(id)
    }
  }
  // 查询角色分配的菜单
  function queryRoleMenu(id) {
    toAssign(id).then(res => {
      if(res && res.data.code === 200) {
        const allPermissions = res.data.data.allPermissions
        const checkedIds = getCheckedIds(allPermissions)
        treeRef.value.setCheckedKeys(checkedIds, false)
      }
    })
  }
  // 得到所有选中的id列表
  function getCheckedIds (auths, initArr = []) {
    return auths.reduce((pre, item) => {
      if (item.select) {
        pre.push(item.id)
        getCheckedIds(item.children, initArr)
      } else if (item.children) {
        getCheckedIds(item.children, initArr)
      }
      return pre
    }, initArr)
  }
  // 查询所有菜单
  function getMenuAll() {
    menuAll().then(res => {
      if(res && res.data.code === 200) {
        treeData.value = res.data.data
      }
    })
  }
  // 通过id查询用户信息
  function queryUserInfo(id) {
    getUserInfo(id).then(res => {
      if(res && res.data.code === 200) {
        const data = res.data.data
        form.id = data.id
        form.roleCode = data.roleCode
        form.roleName = data.roleName
        form.remark = data.remark
      }
    })
  }
  // 将方法暴露给父组件
  defineExpose({
    init
  })

  const formRef = ref(null)
  // 确认
  function handleSaveOrUpdate() {
    formRef.value.validate((valid) => {
      if(!valid) {
        return false
      }
      ElMessageBox.confirm(`确定进行保存操作?`, '提示',{
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        const menuIds = treeRef.value.getCheckedKeys()
        form.permissionList = menuIds
        saveOrUpdate(form).then(res => {
          if(res && res.data.code === 200) {
            dialogFormVisible.value = false
            emit('refreshDataList')
          } else {
            showMessage(res.data.message, 'error')
          }
        })
      }).catch(err => {
        console.log(err)
      })
    })
  }
</script>

<style>
.el-tree__empty-text {
  position: relative !important;
}
</style>
